# 导入相关头文件
import cv2 as cv
import sys

import matplotlib.pyplot as plt
import numpy as np

spr = 2
spc = 3
spn = 0
plt.figure(figsize=[13, 6])


def my_show_image(img, title, trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    plt.title(title)
    if trans is not None:
        img = trans(img)
    plt.axis('off')
    plt.imshow(img, **kwargs)


# ②	读入图片并判断图像是否导入成功
# path = 'image/moon.jpg'
path = '../../../../large_data/CV2/exam/day12/moon.jpg'
img = cv.imread(path, cv.IMREAD_COLOR)
if img is None:
    print('读入图片失败！')
    sys.exit(1)
img_ = img.copy()
my_show_image(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

# ③	图像灰度化
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
my_show_image(img, 'gray', cmap='gray')

# ④	图像二值化处理
# ⑤	二值化处理参数设置合理
ret, bin = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
my_show_image(bin, 'bin', cmap='gray')

# ⑥	形态学核设置合理
# ⑦	进行形态学的变换
kernel = np.ones((5, 5), dtype=np.float32)
opening = cv.morphologyEx(bin, cv.MORPH_OPEN, kernel, iterations=2)
my_show_image(opening, 'opening', cmap='gray')

# ⑧	图像的轮廓提取
contours, hierarchy = cv.findContours(opening, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

# ⑨	图像的轮廓过滤
# ⑩	轮廓过滤的参数设置合理
c_len_arr = np.zeros(len(contours))
for i, c in enumerate(contours):
    c_len = cv.arcLength(c, True)
    c_len_arr[i] = c_len
ordered_idx = np.argsort(c_len_arr)[::-1]
conts = []
for idx in ordered_idx:
    conts.append(contours[idx])
contours = conts[:2]

# ⑪	在原图轮廓周围绘制矩形
bg = cv.cvtColor(opening, cv.COLOR_GRAY2BGR)
for c in contours:
    x, y, w, h = cv.boundingRect(c)
    print(x, y, w, h)
    cv.rectangle(bg, (x, y), (x + w, y + h), (0, 255, 0), 2)
my_show_image(bg, 'contours', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

# ⑫	提取圆的roi区域
# 10934.0 73232.23471713146
# 19317.0 22162.24339268942
# eps = 1e-2
# for c in contours:
#     c_len = cv.arcLength(c, True)
#     r = c_len / 2. / np.pi
#     c_area = cv.contourArea(c)
#     c_area_theory = np.pi * r ** 2
#     print(c_area, c_area_theory)
#     if np.isclose(c_area, c_area_theory, atol=eps):
#         x, y, w, h = cv.boundingRect(c)
#         roi = opening[y:y + h, x:x + w]
#         my_show_image(roi, 'roi', cmap='gray')
#         break
c = contours[1]
x, y, w, h = cv.boundingRect(c)
roi = opening[y:y + h, x:x + w]
my_show_image(roi, 'roi', cmap='gray')

# 13　加入必要注释
